#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <React/RCTEventEmitter.h>

@interface AMapGeoSearch
    : RCTEventEmitter <RCTBridgeModule, AMapSearchDelegate>
@end

@implementation AMapGeoSearch {
  AMapSearchAPI *_manager;
}

RCT_EXPORT_MODULE()

RCT_REMAP_METHOD(init, initWithKey
                 : (NSString *)key
                 : (RCTPromiseResolveBlock)resolve
                 : (RCTPromiseRejectBlock)reject) {
  dispatch_async(dispatch_get_main_queue(), ^{
    [AMapServices sharedServices].apiKey = key;
    if (!(self->_manager)) {
      self->_manager = [[AMapSearchAPI alloc] init];
      self->_manager.delegate = self;
    }
    resolve(nil);
  });
}

RCT_EXPORT_METHOD(searchPOI:(NSDictionary*)locationDict)
{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    CGFloat lat = [[locationDict valueForKey:@"latitude"] floatValue];
    CGFloat lng =[[locationDict valueForKey:@"longitude"] floatValue];
    CGFloat radius =[[locationDict valueForKey:@"radius"] floatValue];
    NSString* searchKey =  [locationDict valueForKey:@"searchKey"];
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    request.radius   = radius;
//    request.types = @"学校";
    request.sortrule = 0;
    request.page     = 1;
    request.offset = 25;
    request.keywords = searchKey;
    [self->_manager AMapPOIAroundSearch:request];
}
RCT_EXPORT_METHOD(searchPOIkeyWord:(NSDictionary*)locationDict)
{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    CGFloat lat = [[locationDict valueForKey:@"latitude"] floatValue];
    CGFloat lng =[[locationDict valueForKey:@"longitude"] floatValue];
    CGFloat radius =[[locationDict valueForKey:@"radius"] floatValue];
    NSString* searchKey =  [locationDict valueForKey:@"searchKey"];
    NSString* cityName =  [locationDict valueForKey:@"city"];
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    request.radius   = radius;
//    request.types = @"学校";
    request.sortrule = 1;
    request.page     = 1;
    request.offset = 25;
    request.keywords = searchKey;
    request.city = cityName;
    [self->_manager AMapPOIAroundSearch:request];
}
RCT_EXPORT_METHOD(reGeocodeSearch:(NSDictionary*)locationDict)
{
    CGFloat lat = [[locationDict valueForKey:@"latitude"] floatValue];
    CGFloat lng =[[locationDict valueForKey:@"longitude"] floatValue];
    AMapReGeocodeSearchRequest * request = [[AMapReGeocodeSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    request.requireExtension = YES;
    [self->_manager AMapReGoecodeSearch:request];
}

RCT_EXPORT_METHOD(showRoute:(NSDictionary*)locationDict)
{
    CGFloat slat = [[locationDict valueForKey:@"slat"] floatValue];
    CGFloat slng =[[locationDict valueForKey:@"slng"] floatValue];
    CGFloat dlat =[[locationDict valueForKey:@"dlat"] floatValue];
    CGFloat dlng =[[locationDict valueForKey:@"dlng"] floatValue];
    int queryType =[[locationDict valueForKey:@"queryType"] intValue];
    if(queryType == 1)
    {
        AMapRidingRouteSearchRequest  * request = [[AMapRidingRouteSearchRequest alloc] init];
        request.destination = [AMapGeoPoint locationWithLatitude:dlat longitude:dlng];
        request.origin = [AMapGeoPoint locationWithLatitude:slat longitude:slng];
        [self->_manager AMapRidingRouteSearch:request];
    }
    else if (queryType == 2)
    {
        AMapWalkingRouteSearchRequest  * request = [[AMapWalkingRouteSearchRequest alloc] init];
        request.destination = [AMapGeoPoint locationWithLatitude:dlat longitude:dlng];
        request.origin = [AMapGeoPoint locationWithLatitude:slat longitude:slng];
        [self->_manager AMapWalkingRouteSearch:request];
    }
    else
    {
        AMapDrivingRouteSearchRequest * request = [[AMapDrivingRouteSearchRequest alloc] init];
        request.destination = [AMapGeoPoint locationWithLatitude:dlat longitude:dlng];
        request.origin = [AMapGeoPoint locationWithLatitude:slat longitude:slng];
        request.strategy = 10;
        [self->_manager AMapDrivingRouteSearch:request];
    }
  
}
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
  //  AMapRouteSearch
    NSInteger duration =   response.route.paths.firstObject.duration;
    NSInteger distance = response.route.paths.firstObject.distance;
    NSArray<AMapStep *> *steps = response.route.paths.firstObject.steps;
    NSInteger count = steps.count;
    NSString* polylines = @"";
    for(int i=0;i<count;++i)
    {
        AMapStep* step = [steps objectAtIndex:i];
        NSString* strPolyline =  step.polyline;
        NSLog(@"%@",strPolyline);
        polylines = [polylines stringByAppendingString:strPolyline];
        if(i<count-1)
        {
            polylines = [polylines stringByAppendingString:@";"];
        }
    }
    [self sendEventWithName:@"AMapRouteSearch" body:@{@"distance":@(distance),@"duration":@(duration),@"polylines":polylines}];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
          //解析response获取地址描述，具体解析见 Demo
          NSLog(@"onReGeocodeSearchDone");
        NSString* name = [NSString stringWithFormat:@"%@", response.regeocode.pois.firstObject.name];
        [self sendEventWithName:@"AMapReGeocodeSearch" body:@{@"city":response.regeocode.addressComponent.city,
                                                              @"address":response.regeocode.formattedAddress,
                                                                @"citycode":response.regeocode.addressComponent.citycode,
                                                                @"adcode":response.regeocode.addressComponent.adcode,
                                                                @"country":response.regeocode.addressComponent.country,
                                                                @"countryCode":response.regeocode.addressComponent.countryCode,
                                                              @"district":response.regeocode.addressComponent.district,
                                                              @"building":response.regeocode.addressComponent.building,
                                                              @"province":response.regeocode.addressComponent.province,
                                                              @"towncode":response.regeocode.addressComponent.towncode,
                                                              @"township":response.regeocode.addressComponent.township,
                                                              @"name":name

        }];
    }
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError");
}
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
     NSLog(@"onPOISearchDone");
    NSMutableArray* mArray = [NSMutableArray array];
    for(int i = 0;i<response.pois.count;++i)
    {
        AMapPOI* poi = response.pois[i];
        NSDictionary* spoi = @{
            @"name":poi.name,
            @"address":poi.address,
            @"city":poi.city,
            @"citycode":poi.citycode,
            @"adcode":poi.adcode,
            @"latitude":@(poi.location.latitude),
            @"longitude":@(poi.location.longitude)};
        [mArray addObject:spoi];
    }
    [self sendEventWithName:@"AMapGeoSearch" body:mArray];
}

- (NSArray<NSString *> *)supportedEvents {
    return @[@"AMapGeoSearch",@"AMapReGeocodeSearch",@"AMapRouteSearch"];
}


@end
